#!/bin/bash

# ================================================================
# TooBit监控系统 - 快速启动脚本 (简化版)
# ================================================================

# 项目路径
PROJECT_ROOT="/Users/austin_w/PycharmProjects/ruoyi-monitor"
BACKEND_JAR="${PROJECT_ROOT}/ChainUp_Monitor_Rear/ruoyi-admin/target/ruoyi-admin.jar"
FRONTEND_DIR="${PROJECT_ROOT}/ChainUp_Monitor_Front"

echo "🚀 启动TooBit监控系统..."

# 检查文件是否存在
if [ ! -f "$BACKEND_JAR" ]; then
    echo "❌ 后端JAR文件不存在，请先编译："
    echo "   cd ${PROJECT_ROOT}/ChainUp_Monitor_Rear"
    echo "   mvn clean package -DskipTests"
    exit 1
fi

if [ ! -d "$FRONTEND_DIR/node_modules" ]; then
    echo "❌ 前端依赖未安装，请先运行："
    echo "   cd $FRONTEND_DIR"
    echo "   npm install"
    exit 1
fi

# 停止可能运行的服务
echo "🛑 停止现有服务..."
pkill -f "ruoyi-admin.jar" 2>/dev/null || true
pkill -f "vue-cli-service serve" 2>/dev/null || true
sleep 2

# 启动后端 (后台)
echo "🔧 启动后端服务..."
cd "$(dirname $BACKEND_JAR)"
nohup java -jar -Xms256m -Xmx1024m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=512m \
    "$(basename $BACKEND_JAR)" > "${PROJECT_ROOT}/backend.log" 2>&1 &
BACKEND_PID=$!
echo "后端PID: $BACKEND_PID"

# 等待后端启动
echo "⏳ 等待后端启动..."
sleep 15

# 启动前端 (后台)
echo "🌐 启动前端服务..."
cd "$FRONTEND_DIR"
nohup npm run dev > "${PROJECT_ROOT}/frontend.log" 2>&1 &
FRONTEND_PID=$!
echo "前端PID: $FRONTEND_PID"

# 等待前端启动
echo "⏳ 等待前端启动..."
sleep 10

echo ""
echo "✅ 启动完成!"
echo "🌐 前端地址: http://localhost:1024"
echo "🔧 后端地址: http://localhost:8080"
echo ""
echo "📊 查看状态: ps aux | grep -E '(ruoyi-admin|vue-cli-service)'"
echo "📝 后端日志: tail -f ${PROJECT_ROOT}/backend.log"
echo "📝 前端日志: tail -f ${PROJECT_ROOT}/frontend.log"
echo "🛑 停止服务: pkill -f 'ruoyi-admin.jar'; pkill -f 'vue-cli-service'"
